//
//  ZDQMApViewController.m
//  CoreDataAddress
//
//  Created by dllo on 15/11/22.
//  Copyright © 2015年 蓝鸥科技. All rights reserved.
//

#import "ZDQMApViewController.h"
#import <BaiduMapAPI_Base/BMKBaseComponent.h>
#import <BaiduMapAPI_Map/BMKMapComponent.h>
#import <BaiduMapAPI_Search/BMKSearchComponent.h>
#import <BaiduMapAPI_Location/BMKLocationComponent.h>
#import "ZDQCoreDataManager.h"
#import "AddressBook.h"

@interface ZDQMApViewController ()<BMKMapViewDelegate, BMKGeoCodeSearchDelegate>
{
    bool isGeoSearch;
}
@property(nonatomic, retain) BMKMapManager *mapManager;
@property(nonatomic, retain) BMKMapView *mapView;
@property(nonatomic, retain) BMKGeoCodeSearch *geocodesearch;
@property(nonatomic, retain) BMKPointAnnotation* pointAnnotation;
@property(nonatomic, strong) ZDQCoreDataManager *manager;
@end

@implementation ZDQMApViewController

- (void)dealloc {
    
    [_mapManager release];
    [_mapView release];
    [_geocodesearch release];
    [_pointAnnotation release];
    [_manager release];
    [super dealloc];
    
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        
        if (_geocodesearch != nil) {
            _geocodesearch = nil;
        }
        
        if (_mapView) {
            
            _mapView = nil;
            
        }
        
    }
    return self;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    // Do any additional setup after loading the view.
    
    self.mapManager = [[BMKMapManager alloc] init];
    BOOL ret = [self.mapManager start:@"d9z2pvEALAN5Bi51bqwohgku" generalDelegate:nil];
    
    if (!ret) {
        
        NSLog(@"manager start failed!");
        
    }
    
    self.mapView = [[BMKMapView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height)];
    self.view = self.mapView;
    
    UILongPressGestureRecognizer *lomgPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(lpngPress:)];
    
    [self.mapView addGestureRecognizer:lomgPress];
    
    _geocodesearch = [[BMKGeoCodeSearch alloc] init];

    NSString *oreillyAddress = self.str;
#pragma mark apple提供的方法 方向地理编码
    CLGeocoder *myGeocoder = [[CLGeocoder alloc] init];
    [myGeocoder geocodeAddressString:oreillyAddress completionHandler:^(NSArray *placemarks, NSError *error) {
        if ([placemarks count] > 0 && error == nil)
        {
            NSLog(@"Found %lu placemark(s).", (unsigned long)[placemarks count]);
            CLPlacemark *firstPlacemark = [placemarks objectAtIndex:0];
            NSLog(@"Longitude = %f", firstPlacemark.location.coordinate.longitude);
            NSLog(@"Latitude = %f", firstPlacemark.location.coordinate.latitude);
            
            if (self.pointAnnotation == nil) {
                self.pointAnnotation = [[BMKPointAnnotation alloc] init];
                CLLocationCoordinate2D coor;
                coor.latitude = firstPlacemark.location.coordinate.latitude;
                coor.longitude = firstPlacemark.location.coordinate.longitude;
                self.pointAnnotation.coordinate = coor;
                self.pointAnnotation.title = self.str;
                _mapView.centerCoordinate = coor;
                
            }
            
            [_mapView addAnnotation:self.pointAnnotation];
            
            
        }
        else if ([placemarks count] == 0 && error == nil)
        {
            NSLog(@"Found no placemarks.");
        }
        else if (error != nil)
        {
            NSLog(@"An error occurred = %@", error);
        }
    }];
    
    
    self.manager = [ZDQCoreDataManager defaults];
    
    NSLog(@"url =========== %@", [self.manager applicationDocumentsDirectory]);
    

    
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"定位" style:UIBarButtonItemStylePlain target:self action:@selector(Action:)];
////
}


- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id <BMKAnnotation>)annotation
{
    //普通annotation
        NSString *AnnotationViewID = @"renameMark";
        BMKPinAnnotationView *annotationView = (BMKPinAnnotationView *)[mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
        if (annotationView == nil) {
            annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
            // 设置颜色
            annotationView.pinColor = BMKPinAnnotationColorPurple;
            // 从天上掉下效果
            annotationView.animatesDrop = YES;
            // 设置可拖拽
            annotationView.draggable = YES;
        
        NSLog(@"!!!!!!!!!%f", self.pointAnnotation.coordinate.latitude);
    }
        return annotationView;
   

}


- (void)lpngPress:(UILongPressGestureRecognizer *)press {
    
    //判断 状态 长按有 两个状态 开始状态 长按结束状态
    if (press.state == UIGestureRecognizerStateEnded) {
        
        //长按结束增加大头针
    BMKPointAnnotation *annotation = [[BMKPointAnnotation alloc] init];
        //获取点击的 坐标 -> 相对的图的视图坐标
        CGPoint point = [press locationInView:self.mapView];
        
        //把这个坐标 转化为 相对于地图的真正经纬度
        annotation.coordinate = [self.mapView convertPoint:point toCoordinateFromView:self.mapView];
        
        //实际上应该根据经纬度 进行地理反编码得到 地址最为大头针数据
        
        annotation.title = [NSString stringWithFormat:@"%f", annotation.coordinate.longitude];
        
        //增加到视图上
        [self.mapView addAnnotation:annotation];
        
        isGeoSearch = false;
        CLLocationCoordinate2D pt = (CLLocationCoordinate2D){annotation.coordinate.latitude, annotation.coordinate.longitude};
        BMKReverseGeoCodeOption *reverseGeocodeSearchOption = [[BMKReverseGeoCodeOption alloc]init];
        reverseGeocodeSearchOption.reverseGeoPoint = pt;
        BOOL flag = [_geocodesearch reverseGeoCode:reverseGeocodeSearchOption];
        if(flag)
        {
            NSLog(@"反geo检索发送成功");
        }
        else
        {
            NSLog(@"反geo检索发送失败");
        }

        
        
    }
    
}

-(void) onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKReverseGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error
{
    NSArray* array = [NSArray arrayWithArray:_mapView.annotations];
    [_mapView removeAnnotations:array];
    array = [NSArray arrayWithArray:_mapView.overlays];
    [_mapView removeOverlays:array];
    if (error == 0) {
        BMKPointAnnotation* item = [[BMKPointAnnotation alloc]init];
        item.coordinate = result.location;
        item.title = result.address;
        [_mapView addAnnotation:item];
        _mapView.centerCoordinate = result.location;
        NSString* titleStr;
        NSString* showmeg;
        titleStr = @"反向地理编码";
        showmeg = [NSString stringWithFormat:@"%@",item.title];
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:titleStr message:showmeg preferredStyle:UIAlertControllerStyleAlert];
                UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        
                }];
                [alertController addAction:action];
        
                [self presentViewController:alertController animated:YES completion:^{
        //

        
                }];
        
        
        // 获取查询数据的请求,相当于数据库的查询语句
        NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"AddressBook"];
        // 添加一个约束 谓词
        NSPredicate *predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ == %@", @"native", @"%@"], self.str];
        //给请求添加约束
        request.predicate = predicate;
        
        NSError *error;
        
        NSArray *array = [self.manager.managedObjectContext executeFetchRequest:request error:&error];
        
        NSLog(@"%@", result.address);
        
        //先进行查找在修改
        for (AddressBook *add in array) {
            add.native = result.address;
        }
        
        [self.manager saveContext];
        NSLog(@"%@", array);

        
        [self.delegate changValue:result.address];
        
        
   }
}



- (void)viewWillAppear:(BOOL)animated {
    [_mapView viewWillAppear];
    _mapView.delegate = self;
    _geocodesearch.delegate = self;
    
    
    
}

- (void)viewWillDisappear:(BOOL)animated {
    [_mapView viewWillDisappear];
    _mapView.delegate = nil;
    _geocodesearch.delegate = nil;
    
}


//- (void)Action:(UIButton *)button {

    
    
    
    
    
//    isGeoSearch = true;
//    BMKGeoCodeSearchOption *geocodeSearchOption = [[BMKGeoCodeSearchOption alloc] init];
//    geocodeSearchOption.address = self.str;
//    //    geocodeSearchOption.city =boo nil;
//    BOOL flag = [_geocodesearch geoCode:geocodeSearchOption];
//
//    if (flag) {
//        
//        NSLog(@"geo检索发送成功");
//        
//    } else {
//        
//        NSLog(@"geo检索发送失败");
//    }
// 
//
    
//    NSString *oreillyAddress = self.str;
//    CLGeocoder *myGeocoder = [[CLGeocoder alloc] init];
//    [myGeocoder geocodeAddressString:oreillyAddress completionHandler:^(NSArray *placemarks, NSError *error) {
//        if ([placemarks count] > 0 && error == nil)
//        {
//            NSLog(@"Found %lu placemark(s).", (unsigned long)[placemarks count]);
//            CLPlacemark *firstPlacemark = [placemarks objectAtIndex:0];
//            NSLog(@"Longitude = %f", firstPlacemark.location.coordinate.longitude);
//            NSLog(@"Latitude = %f", firstPlacemark.location.coordinate.latitude);
//            
//            if (self.pointAnnotation == nil) {
//                self.pointAnnotation = [[BMKPointAnnotation alloc] init];
//                CLLocationCoordinate2D coor;
//                coor.latitude = firstPlacemark.location.coordinate.latitude;
//                coor.longitude = firstPlacemark.location.coordinate.longitude;
//                self.pointAnnotation.coordinate = coor;
//                self.pointAnnotation.title = self.str;
//                _mapView.centerCoordinate = coor;
//                NSLog(@"!!!!!!!!!%@", self.pointAnnotation.title);
//            }
//            
//            [_mapView addAnnotation:self.pointAnnotation];
//            
//            
//        }
//        else if ([placemarks count] == 0 && error == nil)
//        {
//            NSLog(@"Found no placemarks.");
//        }
//        else if (error != nil)
//        {
//            NSLog(@"An error occurred = %@", error);
//        }
//    }];
//    

    
    
//}
//
//

//
//
//- (BMKAnnotationView *)mapView:(BMKMapView *)mapView viewForAnnotation:(id<BMKAnnotation>)annotation {
//    
//    NSString *AnnotationViewID = @"annotationViewID";
//    BMKAnnotationView *annotationView = [mapView dequeueReusableAnnotationViewWithIdentifier:AnnotationViewID];
//    if (annotationView == nil) {
//        annotationView = [[BMKPinAnnotationView alloc] initWithAnnotation:annotation reuseIdentifier:AnnotationViewID];
//        ((BMKPinAnnotationView *)annotationView).pinColor = BMKPinAnnotationColorRed;
//        ((BMKPinAnnotationView *)annotationView).animatesDrop = YES;
//    }
//    
//    annotationView.centerOffset = CGPointMake(0, -(annotationView.frame.size.height * 0.5));
//    annotationView.annotation = annotation;
//    annotationView.canShowCallout = TRUE;
//    return annotationView;
//    
//}
//
//
//
//- (void)onGetGeoCodeResult:(BMKGeoCodeSearch *)searcher result:(BMKGeoCodeResult *)result errorCode:(BMKSearchErrorCode)error {
//    
//    NSLog(@"%@", result);
//    
//    NSArray *array = [NSArray arrayWithArray:_mapView.annotations];
//    [_mapView removeAnnotations:array];
//    array = [NSArray arrayWithArray:_mapView.overlays];
//    [_mapView removeOverlays:array];
//    if (error == 0) {
//        BMKPointAnnotation *item = [[BMKPointAnnotation alloc] init];
//        item.coordinate = result.location;
//        item.title = result.address;
//        [_mapView addAnnotation:item];
//        _mapView.centerCoordinate = result.location;
//        NSString *titleStr;
//        NSString *showMeg;
//        titleStr = @"正向地理编码";
//        showMeg = [NSString stringWithFormat:@"经度:%f, 纬度:%f", item.coordinate.latitude, item.coordinate.longitude];
//        
//        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:titleStr message:showMeg preferredStyle:UIAlertControllerStyleAlert];
//        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//            
//            
//        }];
//        [alertController addAction:action];
//        
//        [self presentViewController:alertController animated:YES completion:^{
//            
//            
//        }];
//        
//    }
//    
//}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
